<template>
  <div class="order-management">
    <div class="header">
      <h2>订单管理</h2>
      <el-button @click="fetchOrders" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <el-table :data="orders" border style="width: 100%" v-loading="loading">
      <el-table-column prop="orderNumber" label="订单号" width="180" />
      <el-table-column prop="userName" label="用户" width="120" />
      <el-table-column prop="totalAmount" label="总金额" width="120">
        <template #default="{ row }">
          ¥{{ row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getOrderStatusType(row.orderStatus)">
            {{ getOrderStatusLabel(row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderType" label="订单类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getOrderTypeType(row.orderType)">
            {{ getOrderTypeLabel(row.orderType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="160">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="票务信息" min-width="300">
        <template #default="{ row }">
          <div v-for="ticket in row.tickets" :key="ticket.id" class="ticket-info">
            <span>{{ ticket.train?.trainNumber }} | </span>
            <span>{{ ticket.startStation?.stationName }} → {{ ticket.endStation?.stationName }} | </span>
            <span>{{ ticket.passengerName }} | </span>
            <span>{{ ticket.seat?.carriageNumber }}车{{ ticket.seat?.seatNumber }}座</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320">
        <template #default="{ row }">
          <el-button 
            size="small" 
            @click="viewOrder(row)"
            type="primary"
          >
            查看详情
          </el-button>
          <el-button 
            v-if="canPay(row)"
            size="small" 
            @click="payOrder(row)"
            type="success"
          >
            付款
          </el-button>
          <el-button 
            v-if="canRefund(row)"
            size="small" 
            @click="refundOrder(row)"
            type="warning"
          >
            退票
          </el-button>
          <el-button 
            v-if="canReschedule(row)"
            size="small" 
            @click="rescheduleOrder(row)"
            type="success"
          >
            改签
          </el-button>
          <el-button 
            v-if="canCancel(row)"
            size="small" 
            @click="cancelOrder(row)"
            type="danger"
          >
            取消订单
          </el-button>
          <el-button 
            v-if="canDelete(row)"
            size="small" 
            @click="deleteOrderRecord(row)"
            type="danger"
          >
            删除记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="orders.length === 0 && !loading" class="no-data">
      暂无订单记录
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="orderDetailVisible" title="订单详情" width="800px">
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ selectedOrder.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(selectedOrder.orderStatus)">
              {{ getOrderStatusLabel(selectedOrder.orderStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单类型">
            <el-tag :type="getOrderTypeType(selectedOrder.orderType)">
              {{ getOrderTypeLabel(selectedOrder.orderType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedOrder.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(selectedOrder.updatedAt) }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin: 20px 0 10px 0">票务详情</h3>
        <el-table :data="selectedOrder.tickets" border>
          <el-table-column prop="passengerName" label="乘客姓名" width="120" />
          <el-table-column prop="passengerIdCard" label="身份证号" width="180" />
          <el-table-column label="车次信息" width="200">
            <template #default="{ row }">
              {{ row.trainNumber }}
            </template>
          </el-table-column>
          <el-table-column label="座位信息" width="150">
            <template #default="{ row }">
              {{ row.carriageNumber }}车{{ row.seatNumber }}座
            </template>
          </el-table-column>
          <el-table-column label="行程信息">
            <template #default="{ row }">
              {{ row.startStationName }} → {{ row.endStationName }}
            </template>
          </el-table-column>
          <el-table-column prop="ticketPrice" label="票价">
            <template #default="{ row }">
              ¥{{ row.ticketPrice }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 退票对话框 -->
    <el-dialog v-model="refundDialogVisible" title="退票申请" width="500px">
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="refundForm.orderNumber" readonly />
        </el-form-item>
        <el-form-item label="退票原因">
          <el-input 
            v-model="refundForm.reason" 
            type="textarea" 
            :rows="3"
            placeholder="请输入退票原因（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund" :loading="refundLoading">
          确认退票
        </el-button>
      </template>
    </el-dialog>

    <!-- 付款对话框 -->
    <el-dialog v-model="paymentDialogVisible" title="订单付款" width="500px">
      <div v-if="paymentForm.order" class="payment-form">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">{{ paymentForm.order.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ paymentForm.order.totalAmount }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-form :model="paymentForm" label-width="100px">
          <el-form-item label="支付方式" required>
            <el-radio-group v-model="paymentForm.paymentMethod">
              <el-radio label="ALIPAY">支付宝</el-radio>
              <el-radio label="WECHAT">微信支付</el-radio>
              <el-radio label="CARD">银行卡</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <el-alert 
          title="这是模拟支付，点击确认付款后将自动完成支付" 
          type="info" 
          :closable="false"
          style="margin: 20px 0"
        />
      </div>
      <template #footer>
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment" :loading="paymentLoading">
          确认付款
        </el-button>
      </template>
    </el-dialog>

    <!-- 改签对话框 -->
    <el-dialog v-model="rescheduleDialogVisible" title="改签申请" width="800px">
      <div class="reschedule-form">
        <h4>原票信息</h4>
        <div v-if="rescheduleForm.originalTicket" class="original-ticket">
          <p><strong>车次：</strong>{{ rescheduleForm.originalTicket.trainNumber }}</p>
          <p><strong>座位：</strong>{{ rescheduleForm.originalTicket.carriageNumber }}车{{ rescheduleForm.originalTicket.seatNumber }}座</p>
          <p><strong>行程：</strong>{{ rescheduleForm.originalTicket.startStationName }} → {{ rescheduleForm.originalTicket.endStationName }}</p>
        </div>

        <el-divider />

        <h4>改签信息</h4>
        <el-form :model="rescheduleForm" label-width="100px">
          <el-form-item label="乘车日期" required>
            <el-date-picker
              v-model="rescheduleForm.travelDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
              @change="searchAvailableTrains"
            />
          </el-form-item>
          
          <el-form-item label="新车次" required v-if="rescheduleForm.travelDate">
            <el-select 
              v-model="rescheduleForm.newTrainId" 
              placeholder="请选择车次"
              style="width: 100%"
              @change="onTrainChange"
              :loading="trainsLoading"
            >
              <el-option
                v-for="train in availableTrains"
                :key="train.id"
                :label="`${train.trainNumber} | ${train.departureTime} - ${train.arrivalTime}`"
                :value="train.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="新座位" required v-if="rescheduleForm.newTrainId">
            <el-select 
              v-model="rescheduleForm.newSeatId" 
              placeholder="请选择座位"
              style="width: 100%"
              :loading="seatsLoading"
            >
              <el-option
                v-for="seat in availableSeats"
                :key="seat.id"
                :label="`${seat.carriageNumber}车${seat.seatNumber}座 (${seat.seatType})`"
                :value="seat.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="改签原因">
            <el-input 
              v-model="rescheduleForm.reason" 
              type="textarea" 
              :rows="3"
              placeholder="请输入改签原因（可选）"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="rescheduleDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmReschedule" 
          :loading="rescheduleLoading"
          :disabled="!rescheduleForm.newTrainId || !rescheduleForm.newSeatId"
        >
          确认改签
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { ticketApi, paymentApi, trainApi, seatApi, stationApi } from '@/api/train'
import type { Order, Ticket, OrderStatus, OrderType, Train, Seat, Station } from '@/types/train'
import { useUserStore } from '@/stores/user'

const loading = ref(false)
const orders = ref<Order[]>([])
const orderDetailVisible = ref(false)
const refundDialogVisible = ref(false)
const rescheduleDialogVisible = ref(false)
const paymentDialogVisible = ref(false)
const refundLoading = ref(false)
const rescheduleLoading = ref(false)
const paymentLoading = ref(false)
const trainsLoading = ref(false)
const seatsLoading = ref(false)

const availableTrains = ref<Train[]>([])
const availableSeats = ref<Seat[]>([])
const allStations = ref<Station[]>([])

const selectedOrder = ref<Order | null>(null)

const refundForm = reactive({
  orderId: 0,
  orderNumber: '',
  reason: ''
})

const rescheduleForm = reactive({
  originalOrderId: 0,
  originalTicket: null as Ticket | null,
  travelDate: '',
  newTrainId: null as number | null,
  newSeatId: null as number | null,
  reason: ''
})

const paymentForm = reactive({
  order: null as Order | null,
  paymentMethod: 'ALIPAY'
})

const userStore = useUserStore()

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    let response
    
    // 根据用户角色获取对应的订单数据
    if (userStore.isAdmin()) {
      // 管理员可以查看所有订单
      response = await ticketApi.getAllOrders()
    } else {
      // 普通用户只能查看自己的订单
      if (!userStore.currentUser?.id) {
        ElMessage.error('用户信息获取失败')
        return
      }
      response = await ticketApi.getOrdersByUserId(userStore.currentUser.id)
    }
    
    if (response.success) {
      orders.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查看订单详情
const viewOrder = (order: Order) => {
  selectedOrder.value = order
  orderDetailVisible.value = true
}

// 退票
const refundOrder = (order: Order) => {
  refundForm.orderId = order.id
  refundForm.orderNumber = order.orderNumber
  refundForm.reason = ''
  refundDialogVisible.value = true
}

// 改签
const rescheduleOrder = (order: Order) => {
  rescheduleForm.originalOrderId = order.id
  rescheduleForm.originalTicket = order.tickets?.[0] || null
  rescheduleForm.travelDate = ''
  rescheduleForm.newTrainId = null
  rescheduleForm.newSeatId = null
  rescheduleForm.reason = ''
  availableTrains.value = []
  availableSeats.value = []
  rescheduleDialogVisible.value = true
}

// 付款
const payOrder = (order: Order) => {
  paymentForm.order = order
  paymentForm.paymentMethod = 'ALIPAY'
  paymentDialogVisible.value = true
}

// 取消订单
const cancelOrder = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消订单 ${order.orderNumber} 吗？取消后将从订单列表中移除。`,
      '确认取消',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    const response = await ticketApi.cancelOrder(order.id)
    if (response.success) {
      ElMessage.success('订单取消成功')
      fetchOrders() // 刷新订单列表
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 删除订单记录
const deleteOrderRecord = async (order: Order) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单 ${order.orderNumber} 的记录吗？删除后将无法恢复。`,
      '确认删除记录',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    const response = await ticketApi.deleteOrder(order.id)
    if (response.success) {
      ElMessage.success('订单记录删除成功')
      fetchOrders() // 刷新订单列表
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单记录失败:', error)
      ElMessage.error('删除订单记录失败')
    }
  }
}

// 确认付款
const confirmPayment = async () => {
  if (!paymentForm.order) {
    ElMessage.error('订单信息错误')
    return
  }

  if (!paymentForm.paymentMethod) {
    ElMessage.warning('请选择支付方式')
    return
  }

  try {
    paymentLoading.value = true
    const response = await paymentApi.processPayment(paymentForm.order.id, paymentForm.paymentMethod)
    
    if (response.success) {
      ElMessage.success('付款成功！')
      paymentDialogVisible.value = false
      fetchOrders() // 刷新订单列表
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('付款失败:', error)
    ElMessage.error('付款失败，请稍后再试')
  } finally {
    paymentLoading.value = false
  }
}

// 确认退票
const confirmRefund = async () => {
  try {
    refundLoading.value = true
    const response = await ticketApi.refundTicket({
      orderId: refundForm.orderId,
      reason: refundForm.reason
    })
    
    if (response.success) {
      ElMessage.success('退票成功')
      refundDialogVisible.value = false
      fetchOrders()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('退票失败:', error)
    ElMessage.error('退票失败')
  } finally {
    refundLoading.value = false
  }
}

// 格式化日期为YYYY-MM-DD格式
const formatDateForApi = (date: string | Date): string => {
  if (!date) return ''
  const d = new Date(date)
  return d.toISOString().split('T')[0]
}

// 搜索可用车次
const searchAvailableTrains = async () => {
  if (!rescheduleForm.travelDate || !rescheduleForm.originalTicket) {
    return
  }

  try {
    trainsLoading.value = true
    const ticket = rescheduleForm.originalTicket
    const formattedDate = formatDateForApi(rescheduleForm.travelDate)
    
    // 先获取所有站点信息
    if (allStations.value.length === 0) {
      const stationsResponse = await stationApi.getAllStations()
      if (stationsResponse.success) {
        allStations.value = stationsResponse.data
      } else {
        ElMessage.error('获取车站信息失败')
        return
      }
    }
    
    // 通过站点名称查找站点ID
    const startStation = allStations.value.find(station => station.stationName === ticket.startStationName)
    const endStation = allStations.value.find(station => station.stationName === ticket.endStationName)
    
    if (!startStation || !endStation) {
      ElMessage.error('无法找到起始或终点站信息')
      return
    }
    
    const response = await trainApi.searchTrains(
      startStation.id,
      endStation.id,
      formattedDate
    )
    
    if (response.success) {
      availableTrains.value = response.data
      rescheduleForm.newTrainId = null
      rescheduleForm.newSeatId = null
      availableSeats.value = []
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('搜索车次失败:', error)
    ElMessage.error('搜索车次失败')
  } finally {
    trainsLoading.value = false
  }
}

// 车次改变时获取可用座位
const onTrainChange = async () => {
  if (!rescheduleForm.newTrainId) {
    availableSeats.value = []
    return
  }

  try {
    seatsLoading.value = true
    const response = await seatApi.getAvailableSeatsByTrainId(rescheduleForm.newTrainId)
    
    if (response.success) {
      availableSeats.value = response.data
      rescheduleForm.newSeatId = null
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取座位失败:', error)
    ElMessage.error('获取座位失败')
  } finally {
    seatsLoading.value = false
  }
}

// 确认改签
const confirmReschedule = async () => {
  if (!rescheduleForm.travelDate) {
    ElMessage.warning('请选择乘车日期')
    return
  }

  if (!rescheduleForm.newTrainId) {
    ElMessage.warning('请选择新车次')
    return
  }

  if (!rescheduleForm.newSeatId) {
    ElMessage.warning('请选择新座位')
    return
  }

  try {
    rescheduleLoading.value = true
    const response = await ticketApi.rescheduleTicket({
      originalOrderId: rescheduleForm.originalOrderId,
      newTrainId: rescheduleForm.newTrainId,
      newSeatId: rescheduleForm.newSeatId,
      travelDate: formatDateForApi(rescheduleForm.travelDate),
      reason: rescheduleForm.reason
    })
    
    if (response.success) {
      ElMessage.success('改签成功')
      rescheduleDialogVisible.value = false
      fetchOrders()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('改签失败:', error)
    ElMessage.error('改签失败')
  } finally {
    rescheduleLoading.value = false
  }
}

// 判断是否可以付款
const canPay = (order: Order) => {
  return order.orderStatus === 'PENDING'
}

// 判断订单中的车票是否已出发
const hasTicketDeparted = (order: Order): boolean => {
  if (!order.tickets || order.tickets.length === 0) return false
  
  const now = new Date()
  // 检查是否有任何一张车票已经出发
  return order.tickets.some(ticket => {
    if (!ticket.departureTime) return false
    
    // 后端返回的departureTime是ISO格式的日期时间字符串
    const departureDateTime = new Date(ticket.departureTime)
    
    // 如果解析失败，则认为未出发（安全起见）
    if (isNaN(departureDateTime.getTime())) {
      console.warn('无法解析车票出发时间:', ticket.departureTime)
      return false
    }
    
    return now > departureDateTime
  })
}

// 判断是否可以退票
const canRefund = (order: Order) => {
  // 只有已付款且车票未出发的订单可以退票
  return order.orderStatus === 'PAID' && !hasTicketDeparted(order)
}

// 判断是否可以改签
const canReschedule = (order: Order) => {
  // 只有已付款且车票未出发的订单可以改签
  return order.orderStatus === 'PAID' && !hasTicketDeparted(order)
}

// 判断是否可以取消订单
const canCancel = (order: Order) => {
  // 只有待付款的订单可以被取消
  return order.orderStatus === 'PENDING'
}

// 判断是否可以删除订单记录
const canDelete = (order: Order) => {
  // 已取消、已退票的订单可以删除记录
  return order.orderStatus === 'CANCELLED' || order.orderStatus === 'REFUNDED'
}

// 获取订单状态标签
const getOrderStatusLabel = (status: OrderStatus) => {
  const statusMap = {
    PENDING: '待付款',
    PAID: '已付款',
    CONFIRMED: '已确认',
    CANCELLED: '已取消',
    REFUNDED: '已退票'
  }
  return statusMap[status] || status
}

// 获取订单状态类型
const getOrderStatusType = (status: OrderStatus) => {
  const typeMap = {
    PENDING: 'warning',
    PAID: 'success',
    CONFIRMED: 'primary',
    CANCELLED: 'info',
    REFUNDED: 'danger'
  }
  return typeMap[status] || 'default'
}

// 获取订单类型标签
const getOrderTypeLabel = (type: OrderType) => {
  const typeMap = {
    DIRECT: '直达',
    TRANSFER: '中转',
    RESCHEDULE: '改签'
  }
  return typeMap[type] || type
}

// 获取订单类型类型
const getOrderTypeType = (type: OrderType) => {
  const typeMap = {
    DIRECT: 'primary',
    TRANSFER: 'warning',
    RESCHEDULE: 'success'
  }
  return typeMap[type] || 'default'
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 获取所有站点信息
const fetchStations = async () => {
  try {
    const response = await stationApi.getAllStations()
    if (response.success) {
      allStations.value = response.data
    } else {
      console.error('获取车站信息失败:', response.message)
    }
  } catch (error) {
    console.error('获取车站信息失败:', error)
  }
}

onMounted(() => {
  fetchOrders()
  fetchStations()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.ticket-info {
  margin-bottom: 5px;
  font-size: 12px;
  color: #606266;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 40px;
}

.order-detail {
  padding: 10px 0;
}

.original-ticket {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin: 10px 0;
}

.original-ticket p {
  margin: 5px 0;
  color: #606266;
}

.reschedule-form h4 {
  margin: 20px 0 10px 0;
  color: #303133;
}

.payment-form {
  padding: 10px 0;
}

.payment-form .el-descriptions {
  margin-bottom: 20px;
}

.payment-form .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style>